/*
 * @Author: Jim <jimjiang0909@gmail.com>
 * @Create time:   2016-08-30 09:55:12
 * @Last Modified by:   Jim
 * @Last Modified time: 2016-08-31 11:14:09
 * @File Name: feedback.js
 */

'use strict';

import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TextInput,
    ActivityIndicator,
    TouchableOpacity,
} from 'react-native';

import ImagePicker from 'react-native-image-picker';

import Select from '../common/select';
import Tips from '../common/tips';

const subjects = ['Identity', 
                'Gold membership / Payment / Billing issues', 
                'Login and password',
                'Registration / Account',
                'Photos / Profile',
                'Matching / Searching',
                'Emails / Messages',
                'Resignation',
                'Technical issues',
                'Suggestions',
                'Complaints',
                'Bugs',
                'Terms of use',
                'Other',
                ];
let { width, height } = Utils.size;

export default class Feedback extends Component {
    constructor(props) {
      super(props);
    
      this.state = {
        activeOpacity: 1,
        subject: '',
        text: '',
        ajax: false,
      };
    }

    shouldComponentUpdate(props, states) {
        let color = '#999', activeOpacity = 1;
        if (states.subject && states.text) {
            color = '#3FAFE4', activeOpacity = 0;
        }
        this.refs.submit.setNativeProps({ style: { backgroundColor: color } });
        states.activeOpacity = activeOpacity;
        return true;

    }

    render() {
        return (
            <View style={styles.container}>
                <View style={[styles.line, {marginTop: 10}]}>
                    <Text style={styles.left}>Topic / Subject:</Text>
                    <Text numberOfLines={1} suppressHighlighting={true} style={[styles.right, styles.rightMaxWidth, {color: '#3FAFE4'}]} onPress={() => this.setState({subjectModalVisble: true})}>{ this.state.subject || 'Please choose' }</Text>
                </View>
                <Text style={{marginTop: 10, color: '#999'}}>Comments:</Text>
                <TextInput 
                    style={styles.input}
                    multiline={true}
                    autoCapitalize={'none'}
                    autoCorrect={false}
                    defaultValue={this.state.text}
                    onChangeText={(text) => this.setState({ text: text }) }
                    placeholder='We will review and respond to your feedback within 24 hours. Please use clear and plain English.' />
                <Text style={[styles.line, styles.left, {marginTop: 10}]}>Attachments </Text>
                <View style={{marginTop: 10}}>
                    <Text style={[styles.left, {fontSize: 11, lineHeight: 16}]}>Do you have a photo or screenshot that would help us? </Text>
                    <Text style={[styles.right, {fontSize: 12}]} onPress={() => this.selectPhoto()} style={{color: '#3FAFE4'}}>Upload it</Text>
                </View>
                { this.state.attachmentSource ? <Image style={{width: 100, height: 100, marginTop: 10}} source={this.state.attachmentSource} /> : null}
                <TouchableOpacity activeOpacity={this.state.activeOpacity} onPress={() => this.ajaxData() }>
                    <View style={styles.botton} ref='submit'>
                        {this.state.ajax ?
                            <ActivityIndicator
                                animating={true}
                                style={styles.centering}
                                size={'small'}
                                color='#fff'
                                />
                            : <Text suppressHighlighting={true} style={styles.submit} >Submit</Text>}
                    </View>
                </TouchableOpacity>
                {this.subjectModal()}
                <Tips ref='tips'/>
            </View>
        )
    }

    getSubjectData() {
        let data = [];
        for(let i in subjects) {
            data.push({value: subjects[i], label: subjects[i]})
        }
        return data;
    }

    subjectModal() {
        return (this.state.subjectModalVisble ? <Select title={'Topic / Subject'} data={this.getSubjectData()} value={this.state.subject} callbackCancel={ () => this.setState({subjectModalVisble: false}) } callbackSave={ (value) => this.setState({subject: value, subjectModalVisble: false}) } /> : null);
    }

   selectPhoto() {
        const options = {
            quality: 0.6,
            maxWidth: 500,
            maxHeight: 500,
            allowsEditing:true,
            storageOptions: {
              skipBackup: true
            }
        };

        ImagePicker.showImagePicker(options, (response) => {
              console.log('Response = ', response);
              if (response.didCancel) {
                console.log('User cancelled photo picker');
              } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
              } else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
              } else {
                let source,imgName;
                imgName = response.uri.split('/').pop();
                // You can display the image using either:
                source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true ,imgName:imgName};
                this.setState({
                    attachmentSource: source,
                });
                //this.uploadPhoto(source);
              }
        });
    }

    ajaxData() {
        let tthis = this;
        if (tthis.state.ajax) return;
        if (this.state.subject && this.state.text) {
            tthis.setState({ajax: true});
            let obj= new FormData();
            obj.append('subject', this.state.subject);
            obj.append('text', this.state.text);

            if(this.state.attachmentSource){
                let file = this.state.attachmentSource;
                obj.append('file', {uri: file.uri, name:file.imgName,type: 'image/jpeg'});
            }

            Share.fetchControl({
                 url : Config.APIURL + 'feedback',
                 fetchOptions : {
                     method: 'POST',
                     headers: {
                        'Content-Type': 'multipart/form-data'
                     },
                     body: obj,
                 },
                 callback : function(data) {
                    console.log(data);
                    tthis.refs.tips.showTips({type: 'success', msg: data.msg });
                    tthis.setState({
                        attachmentSource: null,
                        subject: '',
                        text: '',
                        ajax: false,
                    }); 
                 }
            })
        }

    }  
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        width: width,
        paddingLeft: 10,
        paddingRight: 10,
    },

    line: {
        flexDirection: 'row',
        justifyContent: 'space-between',
    },

    right: {
        color: '#3FAFE4',
        paddingRight: 5,
        textAlign: 'right',
    },

    rightMaxWidth: {        
        width: width - 150,
    },

    left: {
        color: '#999',
    },

    color: {
        color: '#3FAFE4',
    },

    input: {
        backgroundColor: '#fff',
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 5,
        height: 160,
        padding: 5,
        marginTop: 10,
        color: '#3FAFE4',
        fontSize: 16,
    },

    botton: {
        marginTop: 10,
        backgroundColor: '#999',
        height: 40,
        borderRadius: 5,
        justifyContent: 'center',
        alignItems: 'center',

    },

    submit: {
        fontSize: 16,
        color: '#fff',
    },

    centering: {
        alignItems: 'center',
        justifyContent: 'center',
    }
})